package demo;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-02-13
 * Time: 21:03
 */
class IntCmp1 implements Comparator<Integer> {

    public int compare(Integer o1,Integer o2) {
        return o1.compareTo(o2);
    }
}
class IntCmp2 implements Comparator<Integer> {

    public int compare(Integer o1,Integer o2) {
        return o2.compareTo(o1);
    }
}
public class demo1 {
    ////设计一个算法,找出数组中最小的k个数,以任意顺序返回这k个数均可
    //解法一
    /*public int[] smallestK2(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0) return ret;
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(arr.length);
        for(int i = 0;i < arr.length;i++){
            priorityQueue.offer(arr[i]);
        }
        for(int i = 0;i < k;i++){
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }*/
    //解法二
    public static int[] smallestK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0) return ret;
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp1());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            int top = priorityQueue.peek();
            if(arr[i] < top){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }
    ////设计一个算法,找出数组中最大的k个数,以任意顺序返回这k个数均可
    public static int[] MaxK(int[] arr, int k) {
        int[] ret = new int[k];
        if(arr == null || k == 0) return ret;
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCmp1());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            int top = priorityQueue.peek();
            if(arr[i] > top){
                priorityQueue.poll();
                priorityQueue.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] array = {1,2,3,4,52,14,62};
        int k = 3;
        int[] str1 = MaxK(array,k);
        int[] str2 = smallestK(array,k);
        System.out.println(Arrays.toString(str1));
        System.out.println(Arrays.toString(str2));
    }
}
